<!DOCTYPE html>
<html lang="zh-cn">

<head>
<meta charset="utf-8" />
<meta name="author" content="TianShangXing" />
<meta name="description" content="Personal blog." />
<meta name="keywords" content="blog, tech" />
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<meta name="generator" content="Hugo 0.68.3" />

<link rel="canonical" href="https://tianshangxing.gitee.io/myblog/blog/%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0%E9%AA%8C%E8%AF%81%E7%A0%81%E5%8A%9F%E8%83%BD/">
<meta property="og:title" content="代码实现验证码功能" />
<meta property="og:description" content="现在大部分网址登录时都需要输验证码才允许登录，在这里我用python代码来实现手写一套验证码逻辑
Django后端代码 # 导入图片库 # 绘画库 from PIL import ImageDraw # 字体库 from PIL import ImageFont # 图片库 from PIL import Image # 随机库 import random # 文件流 import io # 自定义图片验证码 class MyCode(View): # 定义RGB随机颜色 def get_random_color(self): R = random.randrange(255) G = random.randrange(255) B = random.randrange(255) return(R, G, B) # 定义图片视图 def get(self, request): # 画布 img_size = (130, 60) # 定义图片对象 image = Image.new(&#39;RGB&#39;, img_size, &#39;#FFFFE0&#39;) # 定义画笔 draw = ImageDraw." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://tianshangxing.gitee.io/myblog/blog/%E4%BB%A3%E7%A0%81%E5%AE%9E%E7%8E%B0%E9%AA%8C%E8%AF%81%E7%A0%81%E5%8A%9F%E8%83%BD/" />
<meta property="article:published_time" content="2020-04-29T21:44:36+08:00" />
<meta property="article:modified_time" content="2020-04-29T21:44:36+08:00" />

<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="代码实现验证码功能"/>
<meta name="twitter:description" content="现在大部分网址登录时都需要输验证码才允许登录，在这里我用python代码来实现手写一套验证码逻辑
Django后端代码 # 导入图片库 # 绘画库 from PIL import ImageDraw # 字体库 from PIL import ImageFont # 图片库 from PIL import Image # 随机库 import random # 文件流 import io # 自定义图片验证码 class MyCode(View): # 定义RGB随机颜色 def get_random_color(self): R = random.randrange(255) G = random.randrange(255) B = random.randrange(255) return(R, G, B) # 定义图片视图 def get(self, request): # 画布 img_size = (130, 60) # 定义图片对象 image = Image.new(&#39;RGB&#39;, img_size, &#39;#FFFFE0&#39;) # 定义画笔 draw = ImageDraw."/>


<meta itemprop="name" content="代码实现验证码功能">
<meta itemprop="description" content="现在大部分网址登录时都需要输验证码才允许登录，在这里我用python代码来实现手写一套验证码逻辑
Django后端代码 # 导入图片库 # 绘画库 from PIL import ImageDraw # 字体库 from PIL import ImageFont # 图片库 from PIL import Image # 随机库 import random # 文件流 import io # 自定义图片验证码 class MyCode(View): # 定义RGB随机颜色 def get_random_color(self): R = random.randrange(255) G = random.randrange(255) B = random.randrange(255) return(R, G, B) # 定义图片视图 def get(self, request): # 画布 img_size = (130, 60) # 定义图片对象 image = Image.new(&#39;RGB&#39;, img_size, &#39;#FFFFE0&#39;) # 定义画笔 draw = ImageDraw.">
<meta itemprop="datePublished" content="2020-04-29T21:44:36&#43;08:00" />
<meta itemprop="dateModified" content="2020-04-29T21:44:36&#43;08:00" />
<meta itemprop="wordCount" content="238">



<meta itemprop="keywords" content="" />

<link rel="stylesheet" href="https://tianshangxing.gitee.io/myblog/css/layout.css" />


<link rel="stylesheet" href="https://tianshangxing.gitee.io/myblog/css/default-dark.css" />




<title>


     代码实现验证码功能 

</title>

</head>


<body>
<div class="main">
<header>

<div class="header-bar">

  <nav>
    <div class="siteTitle">
      <a href="https://tianshangxing.gitee.io/myblog">TianShangXing&#39;s Blog</a>
    </div> 

    
    
    <a class="nav-item" href="https://tianshangxing.gitee.io/myblog/blog/"><div class="nav-item-title">Blogs</div></a>
    
    <a class="nav-item" href="https://tianshangxing.gitee.io/myblog/resume/"><div class="nav-item-title">Resume</div></a>
    

  </nav>

  
<div class="social-links-header">

  
  <a href="mailto:tian_shang_xing@foxmail.com"><div class="social-link">email</div></a>
  

  
  <a href="https://github.com/TianShangXing" target="_blank"><div class="social-link">gh</div></a>
  

  

  

  
  <a href="https://www.linkedin.com/in/%e6%98%9f%e4%bc%b8-%e5%88%98-b7b7321a6" target="_blank"><div class="social-link">in</div></a>
  

</div>


</div>


</header>


<article class="post">
    <h1 class="title"> 代码实现验证码功能 </h1>
    <div class="content"> <p>现在大部分网址登录时都需要输验证码才允许登录，在这里我用python代码来实现手写一套验证码逻辑</p>
<h3 id="django后端代码">Django后端代码</h3>
<pre><code># 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

# 自定义图片验证码
class MyCode(View):
	# 定义RGB随机颜色
	def get_random_color(self):
		R = random.randrange(255)
		G = random.randrange(255)
		B = random.randrange(255)

		return(R, G, B)

	# 定义图片视图
	def get(self, request):
		# 画布
		img_size = (130, 60)
		# 定义图片对象
		image = Image.new('RGB', img_size, '#FFFFE0')
		# 定义画笔
		draw = ImageDraw.Draw(image, 'RGB')
		# 定义内容
		source = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
		# 定义字体
		my_font = ImageFont.truetype(font=&quot;c:\\Windows\\Fonts\\comic.ttf&quot;, size=25)
		# 接收容器
		code_str = ''
		# 进入循环绘制
		for i in range(4):
			# 获取字体颜色
			text_color = self.get_random_color()
			# 获取随机下标
			tmp_num = random.randrange(len(source))
			# 随机字符串
			random_str = source[tmp_num]
			# 装入容器中
			code_str += random_str
			# 绘制字符串   坐标(x, y)     随机字符串   字体颜色
			draw.text((10 + 30 * i, 10), random_str, text_color, font=my_font)
		
		# 获取缓冲区
		buf = io.BytesIO()
		# 将临时图片保存到缓冲区
		image.save(buf, 'png')
		# 保存随机码
		r.set('code', code_str)

		#保存session
		request.session['code'] = code_str

		print(r.get('code'))

		return HttpResponse(buf.getvalue(), 'image/png')
</code></pre><h3 id="vue前端代码">vue前端代码</h3>
<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;table&gt;	
        &lt;tr&gt;
            &lt;td&gt;
                验证码:						
            &lt;/td&gt;
            &lt;td&gt;
                &lt;input type=&quot;text&quot; v-model=&quot;code&quot; placeholder=&quot;请输入验证码&quot;&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;td&gt;&lt;/td&gt;
            &lt;td&gt; 
                &lt;img class=&quot;imgcode&quot; alt=&quot;点击刷新&quot; :src=&quot;src&quot;  @click=&quot;changecode&quot;&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  data () {
    return {
		// 验证码图片地址
		src:'http://localhost:8000/code/',
        // 验证码
		code:'',
    }
  },

  methods: {
      // 刷新验证码
  	  changecode:function () {
  		// 生成随机数
  		var num = Math.ceil(Math.random()*10);
  		// 进行传参
  		this.src = this.src + &quot;?num=&quot; + num;
	  },
  }
}

&lt;style&gt;
/* 标签选择器 */
td {
	padding: 5px;
}
.imgcode {
	cursor:pointer;
}
&lt;/style&gt;
</code></pre><p>就是这么简单，最后附上项目地址： <a href="https://github.com/TianShangXing/mydjango">https://github.com/TianShangXing/mydjango</a></p>
 </div>
    <footer class="post-footer">

  <div class="post-footer-data">
            
<div class="tags">
  
</div>

    <div class="date"> 2020-04-29 </div>
    
  </div>
</footer>



</article>

  <footer>

  <div class="social-links-footer">

  
  <a href="mailto:tian_shang_xing@foxmail.com"><div class="social-link">Email</div></a>
  

  
  <a href="https://github.com/TianShangXing" target="_blank"><div class="social-link">GitHub</div></a>
  

  

  

  
  <a href="https://www.linkedin.com/in/%e6%98%9f%e4%bc%b8-%e5%88%98-b7b7321a6" target="_blank"><div class="social-link">LinkedIn</div></a>
  

  <div class="social-link">
  <a href="https://tianshangxing.gitee.io/myblog/index.xml" target="_blank">RSS</a>
  </div>

</div>


  <div class="copyright"> Copyright (c) 2020, all rights reserved. </div>

  <div class="poweredby">
    Powered by <a href="https://gohugo.io/">Hugo</a>.
  </div>

  </footer>

</div> 

</body>
</html>

